package com.gmcas.credentical;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import sun.java2d.pipe.SpanShapeRenderer;

/**
 * Created by zhangshuai on 2017/9/15.
 */
public class SimpleHashedCredentialMatcher extends HashedCredentialsMatcher {

    //存储密码重试次数的cache
    private Cache<String,Integer> passwordRetryCache;

    public SimpleHashedCredentialMatcher(CacheManager cacheManager){
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }

    /**
     * 限制密码重试次数,返回认证结果
     * @param token
     * @param info
     * @return
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = (String)token.getPrincipal();
        Integer time = passwordRetryCache.get(username);

        if(time == null){
            time = 0;
            passwordRetryCache.put(username, 0);
        }

        boolean match = super.doCredentialsMatch(token, info);

        if(match){
            passwordRetryCache.remove(username);
        }else{
            passwordRetryCache.put(username, time += 1);
        }
        //第五次失败后,抛出异常
        if(time >=5){
            throw new ExcessiveAttemptsException("您当前重试次数过多,请明天再试");
        }
        return match;
    }
}
